package com.zxd.interview.netty.towcommunication;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 服务端向客户端主动返回数据
 */
public class FistServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 接受数据处理
        System.out.println(new Date() + "服务端写出数据");
        ctx.writeAndFlush(getByteBuf(ctx));
    }


    private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
        // 1. 获取二进制抽象 Bytebuf
        ByteBuf buffer = ctx.alloc().buffer();

        byte[] bytes = "相关的测试内容 ".getBytes(StandardCharsets.UTF_8);

        // 2. 准备数据 指定字符集
        buffer.writeBytes(bytes);

        // 3. 填充数据到 ByteBuf
        return buffer;
    }
}
